import 'dart:async';

import 'package:casdon/modules/demo/data/repository/demo_repository_impl.dart';
import 'package:casdon/modules/demo/domain/states/demo_orc_state.dart';
import 'package:casdon/modules/me/application/notification/oss_sts_notifier.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class DemoOcrNotifier extends AutoDisposeFamilyNotifier<DemoOcrState, String> {
  @override
  DemoOcrState build(String imagePath) {
    final initialState = DemoOcrState(imagePath: imagePath, isLoading: true);
    _startOcrRecognition(imagePath);
    return initialState;
  }

  Future<void> _startOcrRecognition(String imagePath) async {
    try {
      await _ocrOperation(imagePath);
    } catch (e) {
      state = state.copyWith(isLoading: false, ocrResult: null);
    }
  }

  Future<void> _ocrOperation(String imagePath) async {
    final url = await ref
        .read(ossTokenProvider.notifier)
        .uploadImageForUrl(imagePath);
    if (url == null) return;

    final postRet = await ref.read(demoRepositoryProvider).postRecipeOcr(url);
    int count = 1;
    const interval = Duration(seconds: 1);
    const maxDuration = Duration(seconds: 30);
    final startTime = DateTime.now();

    while (DateTime.now().difference(startTime) < maxDuration) {
      final getResult = await ref
          .read(demoRepositoryProvider)
          .getRecipeOcrRsult(postRet);

      if (getResult != null &&
          getResult.foodJsonCallList != null &&
          getResult.foodJsonCallList!.isNotEmpty) {
        state = state.copyWith(
          ocrResult: getResult,
          isLoading: false,
          imageUrl: url,
        );
        return;
      }
      count = count + 1;
      print('OCR轮询${count}');
      await Future.delayed(interval); // 等待下一次轮询
    }
    state = state.copyWith(isLoading: false, ocrResult: null);

    print('OCR轮询结束');
    return;
  }
}

// Provider 定义
final demoOcrProvider =
    AutoDisposeNotifierProvider.family<DemoOcrNotifier, DemoOcrState, String>(
      DemoOcrNotifier.new,
    );
